package com.netty.clientserver.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author LiuXiaoYu
 * @date 2022/2/2- 13:50
 */
@Component
public class MyWebSocketChannelHandler extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyBindHandler nettyBindHandler;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //添加http专用编解码器
        pipeline.addLast("httpServeCodec",new HttpServerCodec());
         /*HttpObjectAggregator 因为http在传输过程中是分段的，
        HttpObjectAggregator可以将多个段聚合起来,这就是为什么当浏览器发送大量数据时，
        会发出多次http请求*/
        //httpContent消息聚合
        pipeline.addLast("httpObjectAggregator",new HttpObjectAggregator(65536));
        //httpContent压缩
        pipeline.addLast("httpChunkedWrite",new ChunkedWriteHandler());
        /*
         *WebSocketServerProtocolHandler 对应websocket，它的数据是以 帧(frame)形式 传递
         * 可以看到 WebSocketFrame 下有六个子类
         * 浏览器请求时，ws://localhost:8888/XXX 表示请求的资源
         * 核心功能是 将http协议升级为ws协议，保持长连接
         */
        pipeline.addLast("protocolHandler",new WebSocketServerProtocolHandler("/websocket"));
        pipeline.addLast("myWebSocketHandler",myWebSocketHandler);
        pipeline.addLast("bindHandler", nettyBindHandler);

        //netty异常处理器
        pipeline.addLast(NettyExceptionHandler.INSTANCE);

    }
}
